package com.mifengs.mall.ui.openself;

import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.entity.CategoriesBean;
import com.mifengs.mall.entity.City;
import com.mifengs.mall.entity.ContractPre;
import com.mifengs.mall.entity.ImageUpload;
import com.mifengs.mall.entity.ResponseBean;
import com.mifengs.mall.entity.StoreCertificate;
import com.mifengs.mall.event.OpenCompanyEvent;
import com.mifengs.mall.event.OpenSelfEvent;
import com.mifengs.mall.netWork.NetWork;
import com.mifengs.mall.ui.opencompany.AuditFragment;
import com.mifengs.mall.util.GPSUtil;
import com.yiguo.adressselectorlib.AddressSelector;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lynn on 2018/3/23.
 */

public class MaterialSubPresenter implements MaterialSubContract.Presenter {
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static final String TAG = "Material";

    private MaterialSubContract.View mView;

    public MaterialSubPresenter(MaterialSubContract.View mView) {
        this.mView = mView;
    }

    @Override
    public void upLoadImg(List<String> mImgUrls) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i <mImgUrls.size() ; i++) {
            File f=new File(mImgUrls.get(i));
            if (f!=null) {
                builder.addFormDataPart("fileList", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
            }
        }
        builder.addFormDataPart("app_token", PreferenceUtils.getToken());
        builder.addFormDataPart("attachmentType","SIGNATURE");
        List<MultipartBody.Part> parts = builder.build().parts();
        NetWork.getImageUploadApi().uploadFiles(parts)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ImageUpload>bindToLife())
                .subscribe(new Observer<ImageUpload>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
                    }

                    @Override
                    public void onNext(ImageUpload imageUpload) {
                        if(imageUpload.getMsg().equals("OK") || imageUpload.getStatus().equals("1")){
                            System.out.println("上传照片成功：url = " + imageUpload.getResult().getPic());
                        }
                    }
                });
    }

    @Override
    public void getCategories() {
        mView.showLoading();
        NetWork.getMaterialSubApi().getCategories()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<List<CategoriesBean>>bindToLife())
                .subscribe(new Observer<List<CategoriesBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        Log.e("error",e.toString());
                    }

                    @Override
                    public void onNext(List<CategoriesBean> categoriesList) {
                        mView.hideLoading();
                        mView.setCategories(categoriesList);
                    }
                });
    }

    @Override
    public void StoreCertificateSub() {
       final HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("app_token",PreferenceUtils.getToken());
        hashMap.put("contactName",mView.getContactName());
        hashMap.put("contactMobile",mView.getContactPhone());
        hashMap.put("type",mView.getStoreType());
        hashMap.put("companyName",mView.getLicenseName());
        hashMap.put("licenseNumber",mView.getLicenseNumber());
        hashMap.put("isLongTime",mView.intLongTime());
        hashMap.put("licenseStartDate",mView.getLicenseStartDate());
        hashMap.put("licenseEndDate",mView.getLicenseEndDate());
        hashMap.put("company",mView.getBusinessLicenseUrl());
        hashMap.put("name",mView.getStoreName());
        if(!TextUtils.isEmpty(mView.getBankCardPhotoUrl())){
            hashMap.put("card",mView.getSfzPositiveUrl());
        }
        if(!TextUtils.isEmpty(mView.getSfzReverseUrl())){
            hashMap.put("cardback",mView.getSfzReverseUrl());
        }
        if(!TextUtils.isEmpty(mView.getHoldSfzUrl())){
            hashMap.put("handcard",mView.getHoldSfzUrl());
        }
//        hashMap.put("handcard",mView.getHoldSfzUrl());
//        hashMap.put("counter",mView.getStorePhotoOneUrl());
//        hashMap.put("cashierDesk",mView.getStorePhotoTwoUrl());
        hashMap.put("store",mView.getStorePhotoOneUrl());
        hashMap.put("idCardNum",mView.getHeadSfzNum());
        hashMap.put("storeProvinceid",mView.storeProvinceid());
        hashMap.put("storeCityid",mView.storeCityid());
        hashMap.put("storeAreaid",mView.storeAreaid());
        hashMap.put("storeStreetid",mView.storeStreetid());
        hashMap.put("storeAddr",mView.getStoreDetail());
        double[] baiduPoint = GPSUtil.gcj02_To_Bd09(mView.getLatitude(),mView.getLongitude());
        hashMap.put("longitude",baiduPoint[1]);
        hashMap.put("latitude",baiduPoint[0]);
        hashMap.put("storeType1",mView.operateRangeOne());
        hashMap.put("storeType2",mView.operateRangeTwo());
        hashMap.put("bankCardUserName",mView.getBankPleName());
        if(!TextUtils.isEmpty(mView.getBankCardPhotoUrl())){
            hashMap.put("bankCardImg",mView.getBankCardPhotoUrl());
        }
        hashMap.put("bankCardNo",mView.getBankNumber());
        if(mView.getStoreType() ==0){
            hashMap.put("persistent",0);
        }else{
            hashMap.put("persistent",1);
        }
        mView.showLoading();
        NetWork.getMaterialSubApi().saveStoreCertificate(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseBean<ContractPre>>bindToLife())
                .subscribe(new Observer<ResponseBean<ContractPre>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        ToastUitl.show(e.getMessage().toString(),Toast.LENGTH_SHORT);
                        Log.e("error",e.toString());
                    }

                    @Override
                    public void onNext(ResponseBean<ContractPre> contractPreResponseBean) {
                        mView.hideLoading();
                        if(contractPreResponseBean.getStatus().equals(Constant.OK_STATUS)){
                            if(mView.getStoreType()== 0){
                                hashMap.put("hDownloadUrl",contractPreResponseBean.getParamer().getAgreementDownloadUrl());
                                hashMap.put("hPreviewUrl",contractPreResponseBean.getParamer().getAgreementPreviewUrl());
                                hashMap.put("hServer",contractPreResponseBean.getParamer().getAgreementServer());
                                saveData();
                                EventBus.getDefault().post(new OpenSelfEvent(OpenSelfEvent.TOHANDWRITEPAGE,hashMap));
                            }else{//跳转到企业预审
                                OpenCompanyEvent event = new OpenCompanyEvent(OpenCompanyEvent.TO_PRE_AUDIT_PAGE);
                                event.auditStatus = AuditFragment.AuditStatus.AuditIng;
                                PreferenceUtils.saveBooleanPreference(mView.getContext(),MaterialSubFragment.IS_SAVE,false);
                                EventBus.getDefault().post(event);
                            }
                        }else{
                            ToastUitl.show(contractPreResponseBean.getMessage(),Toast.LENGTH_SHORT);
                        }
                    }
                });
    }

    @Override
    public void getStoreCertificate() {
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("app_token",PreferenceUtils.getToken());
        mView.showLoading();
        NetWork.getMaterialSubApi().getStoreCertificate(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseBean<StoreCertificate>>bindToLife())
                .subscribe(new Observer<ResponseBean<StoreCertificate>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        Log.e("error",e.toString());
                    }

                    @Override
                    public void onNext(ResponseBean<StoreCertificate> storeCertificate) {
                        mView.hideLoading();
                        if(storeCertificate.getStatus().equals(Constant.OK_STATUS)){
                            mView.setStoreCertificate(storeCertificate.getParamer(),false);
                        }
                    }
                });
    }

    @Override
    public void getProvinces() {
        mView.showLoading();
        NetWork.getMaterialSubApi().getProvinces()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ArrayList<City>>bindToLife())
                .subscribe(new Observer<ArrayList<City>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        Log.e("error",e.toString());
                    }

                    @Override
                    public void onNext(ArrayList<City> cityListity) {
                        mView.hideLoading();
                        mView.setProvinces(cityListity);
                    }
                });
    }


    @Override
    public void getCitys(int provinceid, final AddressSelector addressSelector, final int postion) {
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("provinceid",provinceid);
        mView.showLoading();
        NetWork.getMaterialSubApi().getCitys(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ArrayList<City>>bindToLife())
                .subscribe(new Observer<ArrayList<City>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        Log.e("error",e.toString());
                    }

                    @Override
                    public void onNext(ArrayList<City> cityListity) {
                        mView.hideLoading();
                        mView.setCitys(cityListity,addressSelector,postion);
                    }
                });
    }

    @Override
    public void getAreas(int cityid, final AddressSelector addressSelector, final int postion) {
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("cityid",cityid);
        mView.showLoading();
        NetWork.getMaterialSubApi().getAreas(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ArrayList<City>>bindToLife())
                .subscribe(new Observer<ArrayList<City>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        Log.e("error",e.toString());
                    }

                    @Override
                    public void onNext(ArrayList<City> cityListity) {
                        mView.hideLoading();
                        mView.setAreas(cityListity,addressSelector,postion);
                    }
                });
    }

    @Override
    public void getStreets(int areaid, final AddressSelector addressSelector, final int postion) {
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("areaid",areaid);
        mView.showLoading();
        NetWork.getMaterialSubApi().getStreets(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ArrayList<City>>bindToLife())
                .subscribe(new Observer<ArrayList<City>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        Log.e("error",e.toString());
                    }

                    @Override
                    public void onNext(ArrayList<City> cityListity) {
                        mView.hideLoading();
                        mView.setStreets(cityListity,addressSelector,postion);
                    }
                });
    }

    @Override
    public void judgeEmpty() {
        if(isEmpty()){
            mView.notEmpty();
        }
    }

    private Boolean isEmpty(){
        String contactName= mView.getContactName();
        String contactMobile= mView.getContactPhone();
        String companyName= mView.getLicenseName();
        String licenseNumber= mView.getLicenseNumber();
        int longTimeType= mView.intLongTime();
        String licenseStartDate= mView.getLicenseStartDate();
        String licenseEndDate= mView.getLicenseEndDate();
        String company= mView.getBusinessLicenseUrl();
        String name= mView.getStoreName();
        String card= mView.getSfzPositiveUrl();
        String cardback= mView.getSfzReverseUrl();
         String bankCardUserName = mView.getBankPleName();
         String bankCardImg = mView.getBankCardPhotoUrl();
         String bankCardNo =mView.getBankNumber();
        String handcard= mView.getHoldSfzUrl();
        String store= mView.getStorePhotoOneUrl();
//        String cashierDesk= mView.getStorePhotoTwoUrl();
//        String store= mView.getStorePhotoThreeUrl();
        String idCardNum= mView.getHeadSfzNum();
        String storeAddr= mView.getStoreDetail()+"";
        String address= mView.getAddress();
        String storeType1= mView.operateRangeOne()+"";
        String storeType2= mView.operateRangeTwo()+"";

        if(contactName == null || "".equals(contactName)){
            ToastUitl.show("联系人姓名未填写", Toast.LENGTH_SHORT);
            return false;
        }else if(contactMobile == null || "".equals(contactMobile)){
            ToastUitl.show("联系人手机未填写", Toast.LENGTH_SHORT);
            return false;
        }else if(contactMobile.length()<11){
            ToastUitl.show("请填写11位手机号码", Toast.LENGTH_SHORT);
            return false;
        }else if(companyName == null || "".equals(companyName)){
            ToastUitl.show("执照名称未填写", Toast.LENGTH_SHORT);
            return false;
        }else if(licenseNumber == null || "".equals(licenseNumber)){
            ToastUitl.show("注册号未填写", Toast.LENGTH_SHORT);
            return false;
        }else if(company == null || "".equals(company)){
            ToastUitl.show("营业执照图片未上传", Toast.LENGTH_SHORT);
            return false;
        }
//        else if(idCardNum == null || "".equals(idCardNum)){
//            ToastUitl.show("负责人身份证号未填写", Toast.LENGTH_SHORT);
//            return false;
//        }else if(idCardNum.length()<16){
//            ToastUitl.show("身份证号位数不够", Toast.LENGTH_SHORT);
//            return false;
//        }else if(card == null || "".equals(card)){
//            ToastUitl.show("身份证正面图片未上传", Toast.LENGTH_SHORT);
//            return false;
//        }else if(cardback == null || "".equals(cardback)){
//            ToastUitl.show("身份证反面图片未上传", Toast.LENGTH_SHORT);
//            return false;
//        }else if(bankCardUserName == null || "".equals(bankCardUserName)){
//            ToastUitl.show("银行卡姓名未填写", Toast.LENGTH_SHORT);
//            return false;
//        }else if(bankCardNo == null || "".equals(bankCardNo)){
//            ToastUitl.show("银行卡未填写", Toast.LENGTH_SHORT);
//            return false;
//        }else if(bankCardImg == null || "".equals(bankCardImg)){
//            ToastUitl.show("银行卡图片未上传", Toast.LENGTH_SHORT);
//            return false;
//        }
//        else if(handcard == null || "".equals(handcard)){
//            ToastUitl.show("身份证手持图片未上传", Toast.LENGTH_SHORT);
//            return false;
//        }
        else if(name == null || "".equals(name)){
            ToastUitl.show("门店名称未填写", Toast.LENGTH_SHORT);
            return false;
        }else if(store == null || "".equals(store)){
            ToastUitl.show("门店图片未上传", Toast.LENGTH_SHORT);
            return false;
        }
//        else if(cashierDesk == null || "".equals(cashierDesk)){
//            ToastUitl.show("门店图片需要上传三张", Toast.LENGTH_SHORT);
//            return false;
//        }else if(store == null || "".equals(store)){
//            ToastUitl.show("门店图片需要上传三张", Toast.LENGTH_SHORT);
//            return false;
//        }
        else if(storeType1 == null || "".equals(storeType1)||"0".equals(storeType1)){
            ToastUitl.show("经营范围一未填写", Toast.LENGTH_SHORT);
            return false;
        }else if(storeType2 == null || "".equals(storeType2) || "0".equals(storeType2)){
            ToastUitl.show("经营范围二未填写", Toast.LENGTH_SHORT);
            return false;
        }else if(address == null || "".equals(address)){
            ToastUitl.show("所在地区未填写", Toast.LENGTH_SHORT);
            return false;
        }else if(storeAddr == null || "".equals(storeAddr)){
            ToastUitl.show("门店详细地址未填写", Toast.LENGTH_SHORT);
            return false;
        }else{
            if(longTimeType == 1){
                if(licenseStartDate == null || "".equals(licenseStartDate)){
                    ToastUitl.show("请填写营业期限日期", Toast.LENGTH_SHORT);
                    return false;
                }else if(licenseEndDate == null || "".equals(licenseEndDate)){
                        ToastUitl.show("请填写营业期限日期", Toast.LENGTH_SHORT);
                        return false;
                }
            }
        }
        return  true;
    }


    @Override
    public void saveData(){
        StoreCertificate storeCertificate = new StoreCertificate();
        StoreCertificate.OpenStore openStore = storeCertificate.new OpenStore();

        openStore.setContactName(mView.getContactName());
        openStore.setContactMobile(mView.getContactPhone());
        openStore.setCompanyName(mView.getLicenseName());
        openStore.setLicenseNumber(mView.getLicenseNumber());
        openStore.setIsLongTime(mView.intLongTime());
        openStore.setLicenseStartDate(mView.getLicenseStartDate());
        openStore.setLicenseEndDate(mView.getLicenseEndDate());
        openStore.setCompany(mView.getBusinessLicenseUrl());
        openStore.setName(mView.getStoreName());
        openStore.setCard(mView.getSfzPositiveUrl());
        openStore.setCardback(mView.getSfzReverseUrl());
        openStore.setHandcard(mView.getHoldSfzUrl());
        openStore.setStore(mView.getStorePhotoOneUrl());
        openStore.setIdCardNum(mView.getHeadSfzNum());
        openStore.setStoreProvinceid(mView.storeProvinceid());
        openStore.setStoreCityid(mView.storeCityid());
        openStore.setStoreAreaid(mView.storeAreaid());
        openStore.setStoreStreetid(mView.storeStreetid());
        openStore.setStoreAddr(mView.getStoreDetail());
        double[] baiduPoint = GPSUtil.gcj02_To_Bd09(mView.getLatitude(),mView.getLongitude());
        openStore.setLongitude(baiduPoint[1]+"");
        openStore.setLatitude(baiduPoint[0]+"");
        openStore.setStoreType1(mView.operateRangeOne());
        openStore.setStoreType2(mView.operateRangeTwo());
        openStore.setBankCardUserName(mView.getBankPleName());
        openStore.setBankCardImg(mView.getBankCardPhotoUrl());
        openStore.setBankCardNo(mView.getBankNumber());

        openStore.setStoreType1Name(mView.getStoreTypeNameOne());
        openStore.setStoreType2Name(mView.getStoreTypeNameTwo());
        openStore.setStoreProvinceName(mView.getStoreProvinceName());
        openStore.setStoreCityName(mView.getStoreCityName());
        openStore.setStoreAreaName(mView.getStoreAreaName());
        openStore.setStoreStreetName(mView.getStoreStreetName());


        storeCertificate.setOpenStoreDTO(openStore);
        PreferenceUtils.saveBooleanPreference(mView.getContext(),MaterialSubFragment.IS_SAVE,true);

        MallApplication.getInstance().getCacheHelper().put(TAG,storeCertificate);
    }





}
